import React, { useState, useRef, useEffect } from 'react';
import { View, Image, Swiper, SwiperItem, Text } from '@tarojs/components';
import Taro, { useDidShow, useDidHide, useUnload } from '@tarojs/taro';
import store from '@/src/store';
import './index.less';

const ImageViewerPage: React.FC = () => {
  const { commonStore } = store as any;
  const imagesRef = useRef<string[]>(commonStore?.images || []);
  const initialIndexRef = useRef<number>(
    Number(commonStore?.initialIndex ?? 0)
  );

  const safeAreaTop = commonStore?.safeAreaTop ?? 0;
  const pageAreaTop = commonStore?.pageAreaTop ?? 0;

  const [images, setImages] = useState<string[]>(imagesRef.current);
  const [current, setCurrent] = useState(0);
  const [duration, setDuration] = useState(300);
  const [forceUpdate, setForceUpdate] = useState(0); // 强制刷新用
  const isPageActiveRef = useRef(false);
  const hasInitializedRef = useRef(false);

  const clampIndex = (idx: number, imgList: string[]) =>
    imgList.length ? Math.max(0, Math.min(idx, imgList.length - 1)) : 0;

  const jumpToInitialIndexNoAnim = () => {
    setDuration(0);
    setCurrent(clampIndex(initialIndexRef.current, imagesRef.current));
    setTimeout(() => setDuration(300), 50);
  };

  // 安全设置导航栏颜色
  const setNavBarColor = (isDark: boolean) => {
    return new Promise((resolve) => {
      try {
        Taro.setNavigationBarColor({
          frontColor: isDark ? '#ffffff' : '#000000',
          backgroundColor: isDark ? '#000000' : '#ffffff',
          animation: {
            duration: 300,
            timingFunc: 'easeInOut',
          },
        })
          .then(() => {
            console.log(`导航栏设置为${isDark ? '深色' : '浅色'}成功`);
            resolve(true);
          })
          .catch((err) => {
            console.warn('设置导航栏颜色失败:', err);
            resolve(false);
          });
      } catch (error) {
        console.warn('设置导航栏颜色异常:', error);
        resolve(false);
      }
    });
  };

  const clearSharedData = () => {
    try {
      if (commonStore) {
        commonStore.images = [];
        commonStore.initialIndex = 0;
      }
    } catch (e) {
      console.warn('清理共享数据失败:', e);
    }
  };

  const handleClose = () => {
    clearSharedData();
    setNavBarColor(false);
    // 延迟一下再返回，确保导航栏设置完成
    setTimeout(() => {
      Taro.navigateBack();
    }, 100);
  };

  // 监听小程序前后台切换（锁屏恢复场景）
  useEffect(() => {
    const handleAppShow = async () => {
      console.log('小程序从后台恢复，页面活跃状态:', isPageActiveRef.current);

      if (isPageActiveRef.current) {
        // 重新设置导航栏
        await setNavBarColor(true);

        // 强制触发重新渲染
        setForceUpdate((prev) => prev + 1);

        // 重新设置图片数据（防止数据丢失）
        if (imagesRef.current.length > 0) {
          setImages([...imagesRef.current]);
          setTimeout(() => {
            setCurrent(clampIndex(current, imagesRef.current));
          }, 50);
        }
      }
    };

    const handleAppHide = () => {
      console.log('小程序进入后台');
    };

    Taro.onAppShow(handleAppShow);
    Taro.onAppHide(handleAppHide);

    return () => {
      Taro.offAppShow(handleAppShow);
      Taro.offAppHide(handleAppHide);
    };
  }, [current]);

  useDidShow(() => {
    console.log('页面显示');
    isPageActiveRef.current = true;

    // 重新获取数据
    const freshImages = commonStore?.images || [];
    const freshIndex = Number(commonStore?.initialIndex ?? 0);

    imagesRef.current = freshImages;
    initialIndexRef.current = freshIndex;

    if (!hasInitializedRef.current) {
      setImages(freshImages);
      hasInitializedRef.current = true;
    }

    setNavBarColor(true);
    jumpToInitialIndexNoAnim();
  });

  useDidHide(() => {
    console.log('页面隐藏');
    isPageActiveRef.current = false;
    setNavBarColor(false);
    clearSharedData();
  });

  useUnload(() => {
    console.log('页面卸载');
    isPageActiveRef.current = false;
    hasInitializedRef.current = false;
    setNavBarColor(false);
    clearSharedData();
  });

  // 如果没有图片数据，显示加载中或返回
  if (!images || images.length === 0) {
    return (
      <View
        className="image-viewer"
        style={{
          paddingTop: `${safeAreaTop}rpx`,
          backgroundColor: '#000000',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <Text style={{ color: '#ffffff' }}>加载中...</Text>
      </View>
    );
  }

  return (
    <View
      className="image-viewer"
      style={{ paddingTop: `${safeAreaTop}rpx` }}
      onClick={handleClose}
      key={forceUpdate} // 使用 key 强制刷新
    >
      {/* 图片左右滑动区 */}
      <View onClick={(e) => e.stopPropagation()} style={{ flex: 1 }}>
        <Swiper
          className="swiper"
          current={current}
          duration={duration}
          onChange={(e) => setCurrent(e.detail.current)}
          indicatorDots={false}
          circular
          autoplay={false}
        >
          {images.map((url, idx) => (
            <SwiperItem key={`${url}-${idx}`}>
              <View className="slide-container">
                <Image
                  src={url}
                  className="slide-image"
                  mode="aspectFit"
                  lazyLoad={false}
                  showMenuByLongpress
                />
              </View>
            </SwiperItem>
          ))}
        </Swiper>
      </View>

      <View
        className="close-btn"
        style={{ top: `${pageAreaTop}rpx` }}
        onClick={handleClose}
      >
        <Image
          className="close-btn-image"
          src="https://file.linkcook.cn/image/wineMiniProgram/imgs/scan/back-white.png"
        />
      </View>

      {/* 顶部页码 */}
      <Text className="counter" style={{ top: `${pageAreaTop}rpx` }}>
        {current + 1}/{images.length}
      </Text>
    </View>
  );
};

export default ImageViewerPage;
